<template>
  <div>
    <!-- 基本图片上传
        el-upload
            action:上传的接口地址，必传参数
            name:上传文件对应的字段名
            show-file-list:是否显示文件列表
            before-upload:上传前的回调，限制 上传文件大小与类型
            on-success:上传成功回调，拿到接口返回值
            http-request:自定义上传 (on-success无效了)
     -->

    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
export default {
  data() {
    return {
      imageUrl: '',
      cos: ''
    }
  },
  created() {
    this.cos = new COS({
      SecretId: 'AKIDpg3Qi3FE1byEJBtNffWClqiT6bwFNVVM',
      SecretKey: 'tkOm196zjH0bCVjpofKmzzqW1JRcaMwL'
    })
  },
  methods: {
    beforeUpload(file) {
      // size  ,type   ,name
      const limitType =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/gif'
      if (!limitType) {
        this.$message.error('请上传png,jpg,gif格式图片')
      }
      const limitSize = file.size / 1024 / 1024 < 100
      if (!limitSize) {
        this.$message.error('请上传100Mb内的图片')
      }
      console.log(file)
      return limitType && limitSize
    },
    httpRequest(res) {
      console.log(res.file)
      this.cos.putObject(
        {
          Bucket: 'hr83-1312526868' /* 必须:存储桶编号 */,
          Region:
            'ap-hongkong' /* 存储桶所在地域，必须字段 ，选择的服务器编号 */,
          Key: '/hm89/' + res.file.name /* 必须:文件名 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 进度值
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 成功或者失败返回值
          console.log(err || data)
          if (!err) {
            this.imageUrl = 'http://' + data.Location
          }
        }
      )
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
